package org.jeecg.modules.order.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.constant.enums.MainErrorEnum;
import org.jeecg.modules.common.CommonUtil;
import org.jeecg.modules.custom.entity.MtCustomEquip;
import org.jeecg.modules.custom.entity.MtCustorm;
import org.jeecg.modules.custom.service.IMtCustomEquipService;
import org.jeecg.modules.custom.service.IMtCustormService;
import org.jeecg.modules.engineer.entity.MtEngineer;
import org.jeecg.modules.engineer.service.IMtEngineerService;
import org.jeecg.modules.order.entity.*;
import org.jeecg.modules.order.service.*;
import org.jeecg.modules.order.vo.MtRepairDisposePage;
import org.jeecg.modules.providers.entity.MtServiceProviders;
import org.jeecg.modules.providers.service.IMtServiceProvidersService;
import org.jeecg.modules.station.entity.MtServiceStation;
import org.jeecg.modules.station.service.IMtServiceStationService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.util.PositionUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.order.vo.MtRepairOrderPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 工单表
 * @Author: jeecg-boot
 * @Date: 2022-09-26
 * @Version: V1.0
 */
@Api(tags = "工单表")
@RestController
@RequestMapping("/order/mtRepairOrder")
@Slf4j
public class MtRepairOrderController {
    @Autowired
    private IMtRepairOrderService mtRepairOrderService;
    @Autowired
    private IMtRepairDispatchService mtRepairDispatchService;
    @Autowired
    private IMtRepairEquipService mtRepairEquipService;
    @Autowired
    private IMtRepairScheduleService mtRepairScheduleService;
    @Autowired
    private IMtRepairFeedbackService mtRepairFeedbackService;
    @Autowired
    private IMtRepairDisposeService mtRepairDisposeService;
    @Autowired
    private IMtCustormService mtCustormService;
    @Autowired
    private IMtCustomEquipService mtCustomEquipService;
    @Autowired
    private IMtEngineerService mtEngineerService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IMtServiceProvidersService mtServiceProvidersService;
    @Autowired
    private IMtServiceStationService mtServiceStationService;
    @Autowired
    private IMtRepairVisitService mtRepairVisitService;
    @Autowired
    private CommonAPI commonAPI;

    /**
     * 分页列表查询
     *
     * @param mtRepairOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "工单表-分页列表查询")
    @ApiOperation(value = "工单表-分页列表查询", notes = "工单表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MtRepairOrder>> queryPageList(MtRepairOrder mtRepairOrder,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        QueryWrapper<MtRepairOrder> queryWrapper = QueryGenerator.initQueryWrapper(mtRepairOrder, req.getParameterMap());
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        // 用户为平台管理员
        if (sysUser.getUserType() == 0) {
            Page<MtRepairOrder> page = new Page<MtRepairOrder>(pageNo, pageSize);
            IPage<MtRepairOrder> pageList = mtRepairOrderService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
        // 用户为服务商
        else if (sysUser.getUserType() == 1) {
            MtServiceProviders loginProviders = mtServiceProvidersService.getOne(new LambdaQueryWrapper<MtServiceProviders>()
                    .eq(MtServiceProviders::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginProviders)) {
                return Result.error("未找到对应服务商");
            }
            queryWrapper.lambda().eq(MtRepairOrder::getProviderId, loginProviders.getId());
        }
        // 用户为工作站
        else if (sysUser.getUserType() == 2) {
            MtServiceStation loginStation = mtServiceStationService.getOne(new LambdaQueryWrapper<MtServiceStation>()
                    .eq(MtServiceStation::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginStation)) {
                return Result.error("未找到对应工作站");
            }
            queryWrapper.lambda().in(MtRepairOrder::getStationId, loginStation.getId());
        }
        // 用户为工程师
        else if (sysUser.getUserType() == 3) {
            MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                    .eq(MtEngineer::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginEngineer)) {
                return Result.error("未找到对应工程师");
            }
            // 获取工程师下属工单信息
            List<MtRepairDispatch> repairDispatchList = mtRepairDispatchService.list(new LambdaQueryWrapper<MtRepairDispatch>()
                    .eq(MtRepairDispatch::getEngineerId, loginEngineer.getId()));
            List<String> orderIds = repairDispatchList.stream().map(MtRepairDispatch::getOrderId).collect(Collectors.toList());
            queryWrapper.lambda().in(MtRepairOrder::getId, orderIds);
        }
        // 用户为客户
        else if (sysUser.getUserType() == 4) {
            MtCustorm loginCustorm = mtCustormService.getOne(new LambdaQueryWrapper<MtCustorm>()
                    .eq(MtCustorm::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginCustorm)) {
                return Result.error("未找到对应商户");
            }
            queryWrapper.lambda().eq(MtRepairOrder::getCustomId, loginCustorm.getId());
        }
        // 其他
        else {
            return Result.error("该用户无权查看");
        }
        Page<MtRepairOrder> page = new Page<MtRepairOrder>(pageNo, pageSize);
        IPage<MtRepairOrder> pageList = mtRepairOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    /**
     * 分页列表查询（我的报修工单）
     *
     * @param mtRepairOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "工单表-分页列表查询")
    @ApiOperation(value = "工单表-分页列表查询（我的报修工单）", notes = "工单表-分页列表查询（我的报修工单）")
    @GetMapping(value = "/myList")
    public Result<IPage<MtRepairOrder>> queryMyPageList(MtRepairOrder mtRepairOrder,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 个人可见
        LambdaQueryWrapper<MtRepairOrder> queryWrapper = QueryGenerator.initQueryWrapper(mtRepairOrder, req.getParameterMap())
                .lambda().eq(MtRepairOrder::getCreateBy, loginUser.getUsername());
        Page<MtRepairOrder> page = new Page<MtRepairOrder>(pageNo, pageSize);
        IPage<MtRepairOrder> pageList = mtRepairOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mtRepairOrderPage
     * @return
     */
    @AutoLog(value = "工单表-添加")
    @ApiOperation(value = "工单表-添加", notes = "工单表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MtRepairOrderPage mtRepairOrderPage) {
        MtRepairOrder mtRepairOrder = new MtRepairOrder();
        BeanUtils.copyProperties(mtRepairOrderPage, mtRepairOrder);
        // 生成工单号
        mtRepairOrder.setOrderNo(CommonUtil.createNo("C"));
        mtRepairOrderService.saveMain(mtRepairOrder, mtRepairOrderPage.getMtRepairDispatchList(), mtRepairOrderPage.getMtRepairEquipList(), mtRepairOrderPage.getMtRepairScheduleList(), mtRepairOrderPage.getMtRepairFeedbackList(), mtRepairOrderPage.getMtRepairDisposeList());
        return Result.OK("添加成功！");
    }

    /**
     * 客户报修
     *
     * @param mtRepairOrderPage
     * @return
     */
    @AutoLog(value = "工单表-客户报修")
    @ApiOperation(value = "工单表-客户报修", notes = "工单表-客户报修")
    @PostMapping(value = "/repair")
    public Result<String> repair(@RequestBody MtRepairOrderPage mtRepairOrderPage) {
        // 获取当前客户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtCustorm loginCustorm = mtCustormService.getOne(new LambdaQueryWrapper<MtCustorm>()
                .eq(MtCustorm::getLinkPhone, loginUser.getUsername()));
        if (Objects.isNull(loginCustorm)) {
            return Result.error("登录客户不存在");
        }
        //验证客户归属的服务商是否存在
        if (StrUtil.isBlank(loginCustorm.getProviderId())) {
            return Result.error("客户未设置服务商！");
        }
        //验证客户是否分配服务站
        if (StrUtil.isBlank(loginCustorm.getStationId())) {
            return Result.error("客户未分配服务站！");
        }

        // 工单信息数据装配
        mtRepairOrderPage.setOrderNo(CommonUtil.createNo("C")) // 生成工单号
                .setOrderSource("3") // 报修来源默认值：web
                .setSkillType("维修") // 工单类型默认值：报修
                .setProcessingStatus("0") // 工单状态默认值：已受理
                .setCustomId(loginCustorm.getId()) // 客户id
                .setBackStatus("0") // 反馈状态默认值：未反馈
                .setProviderId(loginCustorm.getProviderId())// 服务商
                .setStationId(loginCustorm.getStationId());// 服务站
        MtRepairOrder mtRepairOrder = new MtRepairOrder();
        BeanUtils.copyProperties(mtRepairOrderPage, mtRepairOrder);

        // 工单进度数据装配
        List<MtRepairSchedule> mtRepairScheduleList = new ArrayList<>();
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(0)//进度状态：创建
                .setScheduleTime(DateUtil.date());//进度时间
        //进度描述
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + "客户：" + loginCustorm.getCustormName()
                + "创建了" + mtRepairOrderPage.getSkillType() + "工单");
        mtRepairScheduleList.add(mtRepairSchedule);
        // 保存工单数据
        mtRepairOrderService.saveMain(mtRepairOrder, null, null, mtRepairScheduleList, null, null);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mtRepairOrderPage
     * @return
     */
    @AutoLog(value = "工单表-编辑")
    @ApiOperation(value = "工单表-编辑", notes = "工单表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MtRepairOrderPage mtRepairOrderPage) {
        MtRepairOrder mtRepairOrder = new MtRepairOrder();
        BeanUtils.copyProperties(mtRepairOrderPage, mtRepairOrder);
        MtRepairOrder mtRepairOrderEntity = mtRepairOrderService.getById(mtRepairOrder.getId());
        if (mtRepairOrderEntity == null) {
            return Result.error("未找到对应数据");
        }
        mtRepairOrderService.updateMain(mtRepairOrder, mtRepairOrderPage.getMtRepairDispatchList(), mtRepairOrderPage.getMtRepairEquipList(), mtRepairOrderPage.getMtRepairScheduleList(), mtRepairOrderPage.getMtRepairFeedbackList(), mtRepairOrderPage.getMtRepairDisposeList());
        return Result.OK("编辑成功!");
    }


    /**
     * 自动派工
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工单表-自动派工")
    @ApiOperation(value = "工单表-自动派工", notes = "工单表-自动派工")
    @GetMapping(value = "/autoDispatch")
    public Result<String> autoDispatch(@RequestParam(name = "id", required = true) String id) {
        // 筛选出工单数最少的工程师
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(id);
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应数据");
        }
        List<MtEngineer> engineerList = mtEngineerService.list(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getStationId, mtRepairOrder.getStationId()));
        if (engineerList.isEmpty()) {
            return Result.error("工作站下暂无工程师，请手动分配");
        }
        for (MtEngineer engineer : engineerList) {
            engineer.setOrderNum(mtRepairOrderService.getProcessingListByEngineer(engineer.getId()).size());
        }
        Integer minNum = engineerList.stream()
                .map(MtEngineer::getOrderNum)
                .min(Integer::compareTo).orElse(0);
        List<MtEngineer> dispatchEngineerList = engineerList.stream()
                .filter(mtEngineer -> mtEngineer.getOrderNum().equals(minNum))
                .collect(Collectors.toList());
        if (dispatchEngineerList.isEmpty()) {
            return Result.error("无合适工程师");
        }
        int number = RandomUtils.nextInt(dispatchEngineerList.size());
        MtEngineer dispatchEngineer = dispatchEngineerList.get(number);
        // 工单数据补充
        mtRepairOrder.setProcessingStatus("1")//已派工
                .setSysOrgCode(dispatchEngineer.getSysOrgCode());//orgCode绑定

        // 工程师数据装配
        MtRepairDispatch mtRepairDispatch = new MtRepairDispatch();
        mtRepairDispatch.setEngineerId(dispatchEngineer.getId())//绑定工程师
                .setProviderId(dispatchEngineer.getProviderId())//绑定服务商
                .setStationId(dispatchEngineer.getStationId())//绑定服务站
                .setDispatchTime(DateUtil.date())//派工时间
                .setWorkStatus(0)//工作状态默认值：未响应
                .setWorkType("负责");//人员类型：负责


        // 进度跟踪数据装配
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(1)//进度状态：派工
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(dispatchEngineer.getId());//工程师绑定
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + "  编号:" + mtRepairOrder.getOrderNo() + "的工单 自动分配给："
                + mtRepairDispatch.getWorkType() + "-" + dispatchEngineer.getEngineerName() + "。");

        mtRepairOrderService.repairOrderDispatch(mtRepairOrder, mtRepairDispatch, mtRepairSchedule);
        return Result.OK("派工成功!");
    }


    /**
     * 手动派工
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工单表-手动派工")
    @ApiOperation(value = "工单表-手动派工", notes = "工单表-手动派工")
    @GetMapping (value = "/dispatch")
    public Result<String> dispatch(@RequestParam(name = "id", required = true) String id,
                                   @RequestParam(name = "mainEngineerId", required = true) String mainEngineerId,
                                   @RequestParam(name = "engineerIds", required = true) String engineerIds) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        String remarksInfo = "";
        // 用户为服务商
        if (sysUser.getUserType() == 1) {
            remarksInfo = "服务商：" + sysUser.getRealname();// 进度跟踪描述：操作员字段装配
        }
        // 用户为工作站
        else if (sysUser.getUserType() == 2 || sysUser.getUserType() == 3) {
            remarksInfo = "服务站：" + sysUser.getRealname();// 进度跟踪描述：操作员字段装配
        }
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(id);
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应数据");
        }
        if (!"0".equals(mtRepairOrder.getProcessingStatus())) {
            return Result.error("该工单已派工");
        }

        // 获取负责工程师数据
        MtEngineer dispatchEngineer = mtEngineerService.getById(mainEngineerId);
        // 工单数据更新
        mtRepairOrder.setProcessingStatus("1")//已派工
                .setSysOrgCode(dispatchEngineer.getSysOrgCode());//orgCode绑定
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 获取协助工程师数据
        List<MtEngineer> engineerList = mtEngineerService.list(new LambdaQueryWrapper<MtEngineer>()
                .in(MtEngineer::getId, Arrays.asList(engineerIds.split(","))));
        // 工程师数据装配
        StringBuilder remarksEngineer = new StringBuilder();// 进度跟踪描述：工程师字段装配
        mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
        for (MtEngineer engineer : engineerList) {
            MtRepairDispatch repairDispatch = new MtRepairDispatch();
            repairDispatch.setEngineerId(engineer.getId())//绑定工程师
                    .setProviderId(engineer.getProviderId())//绑定服务商
                    .setStationId(engineer.getStationId())//绑定服务站
                    .setDispatchTime(DateUtil.date())//派工时间
                    .setWorkStatus(0)//工作状态默认值：未响应
                    .setWorkType(mainEngineerId.equals(engineer.getId()) ? "负责" : "协同");//人员类型
            mtRepairOrderPage.getMtRepairDispatchList().add(repairDispatch);
            remarksEngineer.append(repairDispatch.getWorkType()).append("-").append(engineer.getEngineerName()).append(" ");// 进度跟踪描述：工程师字段装配
        }

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(1)//进度状态：派工
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(dispatchEngineer.getId());//工程师绑定
        // 进度描述装配
        String remarks = mtRepairSchedule.getScheduleTime()
                + remarksInfo
                + "将编号:" + mtRepairOrder.getOrderNo() + "的工单 "
                + "分配给：" + remarksEngineer;
        mtRepairSchedule.setRemarks(remarks);
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("派工成功!");
    }


    /**
     * 撤销派工
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工单表-撤销派工")
    @ApiOperation(value = "工单表-撤销派工", notes = "工单表-撤销派工")
    @GetMapping(value = "/cancelDispatch")
    public Result<String> cancelDispatch(@RequestParam(name = "id", required = true) String id,
                                         @RequestParam(name = "dispatchId", required = false) String dispatchId,
                                         @RequestParam(name = "dispatchIds", required = true) String dispatchIds) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        String remarksInfo = "";
        // 用户为服务商
        if (sysUser.getUserType() == 1) {
            remarksInfo = "服务商：" + sysUser.getRealname();
        }
        // 用户为工作站
        else if (sysUser.getUserType() == 2 || sysUser.getUserType() == 3) {
            remarksInfo = "服务站：" + sysUser.getRealname();
        }
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(id);
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应数据");
        }
        if (!"1".equals(mtRepairOrder.getProcessingStatus())) {
            return Result.error("该工单无法撤销");
        }
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 更新派工记录
        if (!StrUtil.isBlank(dispatchId)) {
            mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
            MtRepairDispatch dispatch = mtRepairDispatchService.getOne(new LambdaQueryWrapper<MtRepairDispatch>()
                    .eq(MtRepairDispatch::getId, dispatchId));
            dispatch.setWorkType("负责");
            mtRepairOrderPage.getMtRepairDispatchList().add(dispatch);
        }

        // 获取要删除的派工记录
        StringBuilder repair = new StringBuilder();
        List<MtRepairDispatch> deleteDispatch = mtRepairDispatchService.list(new LambdaQueryWrapper<MtRepairDispatch>()
                .in(MtRepairDispatch::getId, (Object[]) dispatchIds.split(",")));
        // 派工记录进度描述装配
        for (MtRepairDispatch dispatch : deleteDispatch) {
            String engineerName = commonAPI.translateDictFromTable("mt_engineer", "engineer_name", "id", dispatch.getEngineerId());
            repair.append(dispatch.getWorkType()).append("-").append(engineerName);
        }

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(1)//进度状态：派工
                .setScheduleTime(DateUtil.date());//进度时间
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + remarksInfo
                + "将编号:" + mtRepairOrder.getOrderNo() + "的工单"
                + "中分配的：" + repair + "撤回");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.repairOrderCancelDispatch(mtRepairOrderPage, deleteDispatch);
        return Result.OK("撤回成功!");
    }


    /**
     * 接单
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工单表-接单")
    @ApiOperation(value = "工单表-接单", notes = "工单表-接单")
    @GetMapping(value = "/accept")
    public Result<String> accept(@RequestParam(name = "id", required = true) String id) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginEngineer)) {
            return Result.error("未找到对应工程师");
        }

        // 派工记录数据更新
        mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
        List<MtRepairDispatch> repairDispatchList = mtRepairDispatchService.list(new LambdaQueryWrapper<MtRepairDispatch>()
                .eq(MtRepairDispatch::getOrderId, id));
        MtRepairDispatch repairDispatch = repairDispatchList.stream()
                .filter(mtRepairDispatch -> mtRepairDispatch.getEngineerId().equals(loginEngineer.getId()))
                .findFirst().orElse(null);
        if (Objects.isNull(repairDispatch)) {
            return Result.error("该工单未派工于该工程师");
        }
        if (repairDispatch.getWorkStatus() != 0) {
            return Result.error("该工程师已接单");
        }
        // 工程师数据装配
        repairDispatch.setWorkStatus(1);//工作状态：已接单
        mtRepairOrderPage.getMtRepairDispatchList().add(repairDispatch);

        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(id);
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        // 工单数据更新
        boolean allMatch = repairDispatchList.stream().allMatch(mtRepairDispatch -> mtRepairDispatch.getWorkStatus() != 0);
        if (allMatch && "1".equals(mtRepairOrder.getProcessingStatus())) {
            mtRepairOrder.setProcessingStatus("2");//工单状态：已接单
        }
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(2)//进度状态：接单
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(loginEngineer.getId());//工程师绑定
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 工程师：" + repairDispatch.getWorkType() + "-" + loginEngineer.getEngineerName()
                + " 接收 编号:" + mtRepairOrder.getOrderNo() + "工单。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("接单成功!");
    }

    /**
     * 到店签到
     *
     * @param id          工单id
     * @param signInCrood 签到地址
     * @return
     */
    @AutoLog(value = "工单表-到店签到")
    @ApiOperation(value = "工单表-到店签到", notes = "工单表-到店签到")
    @GetMapping(value = "/signIn")
    public Result<String> signIn(@RequestParam(name = "id", required = true) String id,
                                 @RequestParam(name = "signInCrood", required = true) String signInCrood) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginEngineer)) {
            return Result.error("未找到对应工程师");
        }
        // 获取工单派工记录
        mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
        List<MtRepairDispatch> repairDispatchList = mtRepairDispatchService.list(new LambdaQueryWrapper<MtRepairDispatch>()
                .eq(MtRepairDispatch::getOrderId, id));
        MtRepairDispatch repairDispatch = repairDispatchList.stream()
                .filter(mtRepairDispatch -> mtRepairDispatch.getEngineerId().equals(loginEngineer.getId()))
                .findFirst().orElse(null);
        if (Objects.isNull(repairDispatch)) {
            return Result.error("该工单未派工于该工程师");
        }
        if (repairDispatch.getWorkStatus() != 1) {
            return Result.error("该工程师已签到");
        }
        // 工单派工记录数据更新
        repairDispatch.setWorkStatus(2);//已签到
        mtRepairOrderPage.getMtRepairDispatchList().add(repairDispatch);

        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(id);
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        // 计算是否到店
        MtCustorm mtCustorm = mtCustormService.getById(mtRepairOrder.getCustomId());
        //longitudeA 第一个点的经度
        //latitudeA  第一个点的纬度
        String[] croods = StringUtils.split(mtCustorm.getCrood(), ",");
        double longitudeA = Double.parseDouble(croods[0]);
        double latitudeA = Double.parseDouble(croods[1]);
        //longitudeB 第二个点的经度
        //latitudeB  第二个点的纬度
        String[] croodsB = StringUtils.split(signInCrood, ",");
        double longitudeB = Double.parseDouble(croodsB[0]);
        double latitudeB = Double.parseDouble(croodsB[1]);
        boolean inCircle = PositionUtil.isInCircle(longitudeA, latitudeA, longitudeB, latitudeB, "500");
        if (!inCircle) {
            return Result.error("尚未到达店铺");
        }

        // 工单数据更新
        boolean allMatch = repairDispatchList.stream().allMatch(mtRepairDispatch -> mtRepairDispatch.getWorkStatus() != 1);
        if (allMatch && "2".equals(mtRepairOrder.getProcessingStatus())) {
            mtRepairOrder.setProcessingStatus("3");//处理中
        }
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(3)//进度状态：处理中
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(loginEngineer.getId());//工程师绑定
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 工程师：" + repairDispatch.getWorkType() + "-" + loginEngineer.getEngineerName()
                + " 于编号:" + mtRepairOrder.getOrderNo() + "工单进行签到");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("签到成功!");
    }


    /**
     * 添加处理记录
     *
     * @param mtRepairDisposePage
     * @return
     */
    @AutoLog(value = "工单表-添加处理记录")
    @ApiOperation(value = "工单表-添加处理记录", notes = "工单表-添加处理记录")
    @PostMapping(value = "/addDispose")
    public Result<String> addDispose(@RequestBody MtRepairDisposePage mtRepairDisposePage) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginEngineer)) {
            return Result.error("未找到对应工程师");
        }
        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(mtRepairDisposePage.getOrderId());
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 派工记录数据更新
        MtRepairDispatch loginDispatch = mtRepairDispatchService.getOne(new LambdaQueryWrapper<MtRepairDispatch>()
                .eq(MtRepairDispatch::getOrderId, mtRepairOrder.getId())
                .eq(MtRepairDispatch::getEngineerId, loginEngineer.getId()));
        mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
        loginDispatch.setWorkStatus(3)//工作状态：已处理
                .setCompletionTime(DateUtil.date());//完工时间
        mtRepairOrderPage.getMtRepairDispatchList().add(loginDispatch);

        // 处理报告数据装配
        mtRepairOrderPage.setMtRepairDisposeList(new ArrayList<>());
        MtRepairDispose mtRepairDispose = new MtRepairDispose();
        mtRepairDispose.setEngineerId(loginEngineer.getId())//工程师
                .setDisposeTime(DateUtil.date())//报告时间
                .setDisposeRemarks(mtRepairDisposePage.getDisposeRemarks())//报告描述
                .setDisposePhoto(mtRepairDisposePage.getDisposePhoto())//照片
                .setStationId(loginEngineer.getStationId())//报告工程师所属服务站
                .setProviderId(loginEngineer.getProviderId())//报告工程师所属服务商
                .setDisposeStatus("3");//报告状态：处理中
        mtRepairOrderPage.getMtRepairDisposeList().add(mtRepairDispose);

        // 处理设备数据装配
        mtRepairOrderPage.setMtRepairEquipList(new ArrayList<>());
        for (MtRepairEquip repairEquip : mtRepairDisposePage.getMtRepairEquipList()) {
            repairEquip.setSubmissTime(DateUtil.date())//提报时间
                    .setOrderType(mtRepairOrder.getSkillType())//与工单类型同样
                    .setEngineerId(loginEngineer.getId())//工程师绑定
                    .setProviderId(loginEngineer.getProviderId())//服务商绑定
                    .setStationId(loginEngineer.getStationId());//工作站绑定
            mtRepairOrderPage.getMtRepairEquipList().add(repairEquip);
        }

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(3)//进度状态：处理中
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(loginEngineer.getId());//工程师绑定
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 工程师：" + loginEngineer.getEngineerName()
                + " 为编号:" + mtRepairOrder.getOrderNo() + "工单提交处理汇报。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("提交成功!");
    }

    /**
     * 修改处理记录
     *
     * @param mtRepairDisposePage
     * @return
     */
    @AutoLog(value = "工单表-修改处理记录")
    @ApiOperation(value = "工单表-修改处理记录", notes = "工单表-修改处理记录")
    @PutMapping(value = "/editDispose")
    public Result<String> editDispose(@RequestBody MtRepairDisposePage mtRepairDisposePage) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginEngineer)) {
            return Result.error("未找到对应工程师");
        }
        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(mtRepairDisposePage.getOrderId());
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 处理报告数据装配
        mtRepairOrderPage.setMtRepairDisposeList(new ArrayList<>());
        MtRepairDispose mtRepairDispose = new MtRepairDispose();
        BeanUtils.copyProperties(mtRepairDisposePage, mtRepairDispose);
        mtRepairOrderPage.getMtRepairDisposeList().add(mtRepairDispose);

        // 处理设备数据装配
        mtRepairOrderPage.setMtRepairEquipList(new ArrayList<>());
        for (MtRepairEquip repairEquip : mtRepairDisposePage.getMtRepairEquipList()) {
            if (StrUtil.isBlank(repairEquip.getId())) {
                repairEquip.setSubmissTime(DateUtil.date())//提报时间
                        .setOrderType(mtRepairOrder.getSkillType())//与工单类型同样
                        .setEngineerId(loginEngineer.getId())//工程师绑定
                        .setProviderId(loginEngineer.getProviderId())//服务商绑定
                        .setStationId(loginEngineer.getStationId());//工作站绑定
            }
            mtRepairOrderPage.getMtRepairEquipList().add(repairEquip);
        }

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(3)//进度状态：处理中
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(loginEngineer.getId());//工程师绑定
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 工程师：" + loginEngineer.getEngineerName()
                + " 将编号:" + mtRepairOrder.getOrderNo() + "工单的处理记录进行修改。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("修改成功!");
    }


    /**
     * 完工
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工单表-完工")
    @ApiOperation(value = "工单表-完工", notes = "工单表-完工")
    @GetMapping(value = "/complete")
    public Result<String> complete(@RequestParam(name = "id", required = true) String id) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginEngineer)) {
            return Result.error("未找到对应工程师");
        }

        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(id);
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        // 工单数据更新
        mtRepairOrder.setProcessingStatus("4")//工单状态：处理完毕待客户确认
                .setUpdateCustomEquip(true);//开启客户设备更新业务
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(4)//进度状态：待客户确认
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(loginEngineer.getId());//工程师绑定
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 工程师：" + "负责-" + loginEngineer.getEngineerName()
                + " 完成了编号:" + mtRepairOrder.getOrderNo() + "工单的处理。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("工单完成!待客户确认");
    }


    /**
     * 客户评价
     *
     * @param mtRepairFeedback
     * @return
     */
    @AutoLog(value = "工单表-客户评价")
    @ApiOperation(value = "工单表-客户评价", notes = "工单表-客户评价")
    @PostMapping(value = "/evaluate")
    public Result<String> evaluate(@RequestBody MtRepairFeedback mtRepairFeedback) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtCustorm loginCustorm = mtCustormService.getOne(new LambdaQueryWrapper<MtCustorm>()
                .eq(MtCustorm::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginCustorm)) {
            return Result.error("未找到对应客户");
        }
        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(mtRepairFeedback.getOrderId());
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        // 工单数据更新
        mtRepairOrder.setProcessingStatus("5");//已完成
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 反馈评价数据装配
        mtRepairOrderPage.setMtRepairFeedbackList(new ArrayList<>());
        mtRepairFeedback.setBackTime(DateUtil.date())//评价时间
                .setCustomId(mtRepairOrder.getCustomId());//评价客户
        mtRepairOrderPage.getMtRepairFeedbackList().add(mtRepairFeedback);

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(5)//进度状态：完成
                .setScheduleTime(DateUtil.date());//进度时间
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 客户：" + loginCustorm.getCustormName() + "为 "
                + " 编号:" + mtRepairOrder.getOrderNo() + "的工单 "
                + " 提交评价。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("评价成功!");
    }

    /**
     * 回访
     *
     * @param mtRepairVisit
     * @return
     */
    @AutoLog(value = "工单表-回访")
    @ApiOperation(value = "工单表-回访", notes = "工单表-回访")
    @PostMapping(value = "/feedback")
    public Result<String> feedback(@RequestBody MtRepairVisit mtRepairVisit) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        String remarksInfo = "";
        // 用户为服务商
        if (sysUser.getUserType() == 1) {
            MtServiceProviders loginProviders = mtServiceProvidersService.getOne(new LambdaQueryWrapper<MtServiceProviders>()
                    .eq(MtServiceProviders::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginProviders)) {
                return Result.error("未找到对应服务商");
            }
            remarksInfo = "服务商：" + loginProviders.getProName();
        }
        // 用户为工作站
        else if (sysUser.getUserType() == 2) {
            MtServiceStation loginStation = mtServiceStationService.getOne(new LambdaQueryWrapper<MtServiceStation>()
                    .eq(MtServiceStation::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginStation)) {
                return Result.error("未找到对应工作站");
            }
            remarksInfo = "工作站：" + loginStation.getStationName();
        } else {
            return Result.error("该用户非服务商/服务站");
        }

        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(mtRepairVisit.getOrderId());
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        // 工单数据更新
        mtRepairOrder.setProcessingStatus("6");//已归档
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 回访记录数据装配
        mtRepairOrderPage.setMtRepairVisitList(new ArrayList<>());
        mtRepairVisit.setProviderId(mtRepairOrder.getProviderId())
                .setStationId(mtRepairOrder.getStationId())
                .setFeedbackTime(DateUtil.date())
                .setCustomId(mtRepairOrder.getCustomId())
                .setFeedbackUser(loginUser.getUsername());
        mtRepairOrderPage.getMtRepairVisitList().add(mtRepairVisit);

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(6)//进度状态：归档
                .setScheduleTime(DateUtil.date());//进度时间
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + remarksInfo
                + "对编号:" + mtRepairOrder.getOrderNo() + "的工单"
                + "回访完成，进行归档。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("回访完成!");
    }


    /**
     * 根据工单id获取当前工程师派工记录
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据工单id获取当前工程师派工记录", notes = "根据工单id获取当前工程师派工记录")
    @GetMapping(value = "/getLoginRepairDispatchByOrderId")
    public Result getLoginRepairDispatchByOrderId(@RequestParam(name = "id", required = true) String id) {
        // 获取登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        // 用户为工程师
        if (sysUser.getUserType() == 3) {
            MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                    .eq(MtEngineer::getUserId, sysUser.getUsername()));
            MtRepairDispatch repairDispatch = mtRepairDispatchService.getOne(new LambdaQueryWrapper<MtRepairDispatch>()
                    .eq(MtRepairDispatch::getOrderId, id)
                    .eq(MtRepairDispatch::getEngineerId, loginEngineer.getId()));
            return Result.OK(repairDispatch);
        }
        return Result.OK();
    }


    /**
     * 根据工单id获取当前工程师处理记录
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据工单id获取当前工程师处理记录", notes = "根据工单id获取当前工程师处理记录")
    @GetMapping(value = "/getLoginRepairDisposeByOrderId")
    public Result getLoginRepairDisposeByOrderId(@RequestParam(name = "id", required = true) String id) {
        // 获取登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        // 用户为工程师
        if (sysUser.getUserType() == 3) {
            MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                    .eq(MtEngineer::getUserId, sysUser.getUsername()));
            MtRepairDispose repairDispose = mtRepairDisposeService.getOne(new LambdaQueryWrapper<MtRepairDispose>()
                    .eq(MtRepairDispose::getOrderId, id)
                    .eq(MtRepairDispose::getEngineerId, loginEngineer.getId()));
            return Result.OK(repairDispose);
        }
        return Result.OK();
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工单表-通过id删除")
    @ApiOperation(value = "工单表-通过id删除", notes = "工单表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        mtRepairOrderService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "工单表-批量删除")
    @ApiOperation(value = "工单表-批量删除", notes = "工单表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mtRepairOrderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工单表-通过id查询")
    @ApiOperation(value = "工单表-通过id查询", notes = "工单表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MtRepairOrder> queryById(@RequestParam(name = "id", required = true) String id) {
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(id);
        if (mtRepairOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mtRepairOrder);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工单派工通过主表ID查询")
    @ApiOperation(value = "工单派工主表ID查询", notes = "工单派工-通主表ID查询")
    @GetMapping(value = "/queryMtRepairDispatchByMainId")
    public Result<List<MtRepairDispatch>> queryMtRepairDispatchListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairDispatch> mtRepairDispatchList = mtRepairDispatchService.list(new LambdaQueryWrapper<MtRepairDispatch>().eq(MtRepairDispatch::getOrderId, id));
        return Result.OK(mtRepairDispatchList);
    }

    /**
     * 获取工单派工记录
     *
     * @param mtRepairDispatch
     * @return
     */
    //@AutoLog(value = "工单派工通过主表ID查询")
    @ApiOperation(value = "获取工单派工记录", notes = "工单派工-获取工单派工记录")
    @GetMapping(value = "/queryMtRepairDispatch")
    public Result<IPage<MtRepairDispatch>> queryMtRepairDispatchList(MtRepairDispatch mtRepairDispatch,
                                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                     HttpServletRequest req) {
        QueryWrapper<MtRepairDispatch> queryWrapper = QueryGenerator.initQueryWrapper(mtRepairDispatch, req.getParameterMap());
        Page<MtRepairDispatch> page = new Page<>(pageNo, pageSize);
        Page<MtRepairDispatch> pageList = mtRepairDispatchService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工单设备通过主表ID查询")
    @ApiOperation(value = "工单设备主表ID查询", notes = "工单设备-通主表ID查询")
    @GetMapping(value = "/queryMtRepairEquipByMainId")
    public Result<List<MtRepairEquip>> queryMtRepairEquipListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairEquip> mtRepairEquipList = mtRepairEquipService.list(new LambdaQueryWrapper<MtRepairEquip>().eq(MtRepairEquip::getOrderId, id));
        return Result.OK(mtRepairEquipList);
    }


    /**
     * 根据订单id查询登录工程师id
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工单设备通过主表ID查询")
    @ApiOperation(value = "根据订单id查询登录工程师id", notes = "工单设备-根据订单id查询登录工程师id")
    @GetMapping(value = "/queryEngineerRepairEquipListByOrderId")
    public Result<List<MtRepairEquip>> queryEngineerRepairEquipListByOrderId(@RequestParam(name = "id", required = true) String id) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginEngineer)) {
            return Result.error("未找到对应工程师");
        }
        List<MtRepairEquip> mtRepairEquipList = mtRepairEquipService.list(new LambdaQueryWrapper<MtRepairEquip>()
                .eq(MtRepairEquip::getOrderId, id)
                .eq(MtRepairEquip::getEngineerId, loginEngineer.getId()));
        return Result.OK(mtRepairEquipList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工单进度通过主表ID查询")
    @ApiOperation(value = "工单进度主表ID查询", notes = "工单进度-通主表ID查询")
    @GetMapping(value = "/queryMtRepairScheduleByMainId")
    public Result<List<MtRepairSchedule>> queryMtRepairScheduleListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairSchedule> mtRepairScheduleList = mtRepairScheduleService.list(new LambdaQueryWrapper<MtRepairSchedule>().eq(MtRepairSchedule::getOrderId, id));
        return Result.OK(mtRepairScheduleList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工单反馈通过主表ID查询")
    @ApiOperation(value = "工单反馈主表ID查询", notes = "工单反馈-通主表ID查询")
    @GetMapping(value = "/queryMtRepairFeedbackByMainId")
    public Result<List<MtRepairFeedback>> queryMtRepairFeedbackListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairFeedback> mtRepairFeedbackList = mtRepairFeedbackService.list(new LambdaQueryWrapper<MtRepairFeedback>().eq(MtRepairFeedback::getOrderId, id));
        return Result.OK(mtRepairFeedbackList);
    }

    /**
     * 通过工单id查询（带字典翻译）
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "工单反馈-工单ID查询", notes = "工单反馈-通过工单ID查询")
    @GetMapping(value = "/queryMtRepairFeedbackListByOrderId")
    public Result<List<MtRepairFeedback>> queryMtRepairFeedbackListByOrderId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairFeedback> mtRepairFeedbackList = mtRepairFeedbackService.list(new LambdaQueryWrapper<MtRepairFeedback>()
                .eq(MtRepairFeedback::getOrderId, id).orderByDesc(MtRepairFeedback::getBackTime));
        return Result.OK(mtRepairFeedbackList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工单处理通过主表ID查询")
    @ApiOperation(value = "工单处理主表ID查询", notes = "工单处理-通主表ID查询")
    @GetMapping(value = "/queryMtRepairDisposeByMainId")
    public Result<List<MtRepairDispose>> queryMtRepairDisposeListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairDispose> mtRepairDisposeList = mtRepairDisposeService.list(new LambdaQueryWrapper<MtRepairDispose>().eq(MtRepairDispose::getOrderId, id));
        return Result.OK(mtRepairDisposeList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工单处理通过主表ID查询")
    @ApiOperation(value = "工单处理主表ID查询", notes = "工单处理-通主表ID查询")
    @GetMapping(value = "/queryMtRepairVisitListByMainId")
    public Result<List<MtRepairVisit>> queryMtRepairVisitListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairVisit> mtRepairVisitList = mtRepairVisitService.list(new LambdaQueryWrapper<MtRepairVisit>().eq(MtRepairVisit::getOrderId, id));
        return Result.OK(mtRepairVisitList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mtRepairOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MtRepairOrder mtRepairOrder) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<MtRepairOrder> queryWrapper = QueryGenerator.initQueryWrapper(mtRepairOrder, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<MtRepairOrder> mtRepairOrderList = mtRepairOrderService.list(queryWrapper);

        // Step.3 组装pageList
        List<MtRepairOrderPage> pageList = new ArrayList<MtRepairOrderPage>();
        for (MtRepairOrder main : mtRepairOrderList) {
            MtRepairOrderPage vo = new MtRepairOrderPage();
            BeanUtils.copyProperties(main, vo);
            List<MtRepairDispatch> mtRepairDispatchList = mtRepairDispatchService.selectByMainId(main.getId());
            vo.setMtRepairDispatchList(mtRepairDispatchList);
            List<MtRepairEquip> mtRepairEquipList = mtRepairEquipService.selectByMainId(main.getId());
            vo.setMtRepairEquipList(mtRepairEquipList);
            List<MtRepairSchedule> mtRepairScheduleList = mtRepairScheduleService.selectByMainId(main.getId());
            vo.setMtRepairScheduleList(mtRepairScheduleList);
            List<MtRepairFeedback> mtRepairFeedbackList = mtRepairFeedbackService.selectByMainId(main.getId());
            vo.setMtRepairFeedbackList(mtRepairFeedbackList);
            List<MtRepairDispose> mtRepairDisposeList = mtRepairDisposeService.selectByMainId(main.getId());
            vo.setMtRepairDisposeList(mtRepairDisposeList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "工单表列表");
        mv.addObject(NormalExcelConstants.CLASS, MtRepairOrderPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("工单表数据", "导出人:" + sysUser.getRealname(), "工单表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MtRepairOrderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), MtRepairOrderPage.class, params);
                for (MtRepairOrderPage page : list) {
                    MtRepairOrder po = new MtRepairOrder();
                    BeanUtils.copyProperties(page, po);
                    mtRepairOrderService.saveMain(po, page.getMtRepairDispatchList(), page.getMtRepairEquipList(), page.getMtRepairScheduleList(), page.getMtRepairFeedbackList(), page.getMtRepairDisposeList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
